<?php

App::uses('GenericUtil', 'Lib');
App::import('Vendor', 'phpThumb', array('file' => 'phpThumb/phpthumb.class.php')); 


class AttachUtil {
	
	public static function upload(&$attach, $inputFile,$codiceAttachTipo,$pathDinamico=null) {
		// $ds = null;
		try {
		    // $ds = $attach->getDataSource();
			// $ds->begin();
       		if (isset($inputFile["name"]) && !empty($inputFile["name"])) {
       		    $newName = GenericUtil::generate_key(8) .".". pathinfo($inputFile['name'], PATHINFO_EXTENSION);
				$attach->set('original_name', $inputFile["name"]);
				$attach->set('file_name', $newName);
				$attach->set('attach_tipo', $codiceAttachTipo);
				$attach->set('dimensione', $inputFile["size"]);
				$attach->set('tipo', $inputFile["type"]);
				$attach->set('path_dinamico',$pathDinamico);

				if ($attach->attachTipo==null) {
					$attach->attachTipo = new AttachTipo();
					$attach->attachTipo->read(null,$codiceAttachTipo);
				}
				// verifico se le il file ha le stesse estensioni configurate sul tipo attach
            	$validExtensions = split(",", $attach->attachTipo->data['AttachTipo']['estensioni']);
                if(!in_array(strtolower(pathinfo($inputFile['name'], PATHINFO_EXTENSION)), $validExtensions))
					throw new Exception(__("Estensione del file %s non corretta, file richiesti: %s", $inputFile['name'],$attach->attachTipo->data['AttachTipo']['estensioni']));
				
				$tmpFile = TMP."uploads".DS.pathinfo($inputFile["tmp_name"],PATHINFO_BASENAME);
				// pr($tmpFile);die;
				$success = move_uploaded_file($inputFile["tmp_name"], $tmpFile);
				if (!$success) {
					throw new Exception(__("Errore in fase di copia dell'attach sulla cartella tmp."));
				}

				// fare esclusivamente se è impostato il thumbfile
				if ($attach->attachTipo->data['AttachTipo']['thumb']) {
					// $exif=exif_read_data(TMP."uploads".DS.pathinfo($inputFile["tmp_name"],PATHINFO_BASENAME));
					// CakeLog::debug("exif image uploaded: ". print_r($exif,true));
			        $phpThumb = new phpthumb();
			        $phpThumb->setSourceFilename($tmpFile);
			        $phpThumb->setParameter('w',800);
			        // $phpThumb->setParameter('ra',"360"); 
			        $phpThumb->setParameter('ar','x'); 
			        // $phpThumb->setParameter('xto','EXIF'); 
			        // $phpThumb->setParameter('h',600); 
			        if($phpThumb->generateThumbnail()){ 
			            if(!$phpThumb->RenderToFile($tmpFile)) {
							CakeLog::error("Render del file ".$path.DS."thumb_".$filename." fallito: " . implode(">", $phpThumb->debugmessages));
			            	throw new Exception(__("Render del file %s fallito.",$path.DS."thumb_".$filename)); 
			            } 
			        } else {
						CakeLog::error(__("Non è stato possibile generare thumbnail:") . implode(">", $phpThumb->debugmessages));
			            throw new Exception(__("L'immagine potrebbe essere troppo grande, diminuire il formato.")); 
			        } 
				}

				$attach->setFileTemporaneo($tmpFile,true);
				// pr($attach->data);die;
				if (!$attach->save()) {
					if ($attach->getFile())
						$attach->deleteFile();
					throw new Exception(__("File %s non salvato.",$inputFile["name"]));
				}
				// $ds->commit();
    		} else {
    			throw new Exception(__("File non selezionato."));
    		}
    	} catch (Exception $e) {
	    	// if (isset($ds))
	    		// $ds->rollback();
			CakeLog::error($e->getMessage());
			throw $e;
    	}
	}
	
	public static function saveAttachFromFile(&$attach, $file, $codiceAttachTipo,$pathDinamico=null) {
    	try {
       		if (!empty($file) && !empty($codiceAttachTipo)) {
				$attach->set('file_name', pathinfo($file,PATHINFO_BASENAME));
				$attach->set('attach_tipo', $codiceAttachTipo);
				$attach->set('dimensione', filesize($file));
				$attach->set('tipo', pathinfo($file,PATHINFO_EXTENSION));
				$attach->set('path_dinamico',$pathDinamico);
				$attach->setFileTemporaneo($file);
				$attach->save();
				return true;
    		} else {
    			return false;
    		}
    	} catch (exception $e) {
			CakeLog::error($e->getMessage());
			throw $e;
    	}
	}
	
	public static function download_file ($url, $path) {
	  $filename = basename($url);
	  $fullname = $path . $filename;

	  $file = file_get_contents($url);

	  file_put_contents($file, $fullname);

	  // $file = fopen ($url, "rb");
	  // if ($file) {
	    // $newfile = fopen ($newfilename, "wb");
	    // if ($newfile)
		    // while(!feof($file)) {
		      // fwrite($newfile, fread($file, 1024 * 8 ), 1024 * 8 );
	    // }
	  // } else {
		  // throw new NotFoundException();
	  // }
	  // if ($file) {
	    // fclose($file);
	  // }
	  // if ($newfile) {
	    // fclose($newfile);
	  // }
	  
	  return $fullname;
	 }	
	
	public static function saveAttachFromUrl(&$attach, $url, $codiceAttachTipo, $pathDinamico=null) {
    	try {
       		if (!empty($url)) {
				$downloadedFile = AttachUtil::download_file($url, TMP."uploads/");
  				$attach->setFileTemporaneo($downloadedFile);
				$attach->set('file_name', pathinfo($downloadedFile,PATHINFO_BASENAME));
				$attach->set('attach_tipo', $codiceAttachTipo);
				$attach->set('dimensione', filesize($downloadedFile));
				$attach->set('tipo', pathinfo($downloadedFile,PATHINFO_EXTENSION));
				$attach->set('path_dinamico',$pathDinamico);
				$attach->save();
				return true;
    		} else {
    			return false;
    		}
    	} catch (exception $e) {
			CakeLog::error($e->getMessage());
			throw $e;
    	}
	}
	

	// sposta un dato attach in un altro tipo
	public static function moveAttach($attach,$attachTipo) {
		try {
			$attachSource = null;
			$attachDest = null;
			if ($attach instanceof Attach) {
				$attachSource = $attach;
			} else {
				$attachSource = new Attach();
				$attachSource->read(null,$attach);
			}
			$attachDest=$this->copyAttach($attachSource,$attachTipo);
			$attachSource->delete();
		} catch (exception $e) {
			CakeLog::error($e->getMessage());
			throw $e;
		}
	}

	// copia attach
	public static function copyAttach($attach, $attachTipo) {
		try {
			$attachSource = null;
			$attachDest = null;
			if ($attach instanceof Attach) {
				$attachSource = $attach;
			} else {
				$attachSource = new Attach();
				$attachSource->read(null,$attach);
			}
			// verifico che l'attach dato non sia dello stesso tipo
			if ($attachSource->data["Attach"]["attach_tipo"]==$attachTipo) {
				throw new Exception(__("Impossibile spostare un attach dello stesso tipo."));
			}
			$attachDest = new Attach();
			$this->copyAttachModel($attachSource, $attachDest);
			$attachDest->set("attach_tipo",$attachTipo);
			$attachDest->setFileTemporaneo($attachSource->getFile(),false);
			$attachDest->save();
			return $attachDest;
		} catch (exception $e) {
			CakeLog::error($e->getMessage());
			throw $e;
		}
	}

	private function copyAttachModel($src,$dest) {
		$dest->set("file_name",$src->data["Attach"]["file_name"]);
		$dest->set("path",$src->data["Attach"]["path"]);
		$dest->set("dimensione",$src->data["Attach"]("dimensione"));
		$dest->set("tipo",$src->data["Attach"]["tipo"]);
		$dest->set("descrizione",$src->data["Attach"]["descrizione"]);
		$dest->set("ordine",$src->data["Attach"]["ordine"]);
		$dest->set("visibile",$src->data["Attach"]["visibile"]);
	}
	
}

?>